<template>
	<div class="scroll-box">
		<ul ref="parent" class="infinity-scroll">
			<li 
			  class="infinity-scroll-item"
			  v-for="(li, i) in venderList"
			  :key="i"
			  :ref="getElementId(i)"
			  :id="getElementId(i)"
			>
				<span v-text="i+cIndex"></span>
				--
				<span v-text="li.name"></span>
				--
				<span v-text="li.age"></span>
			</li>
		</ul>
	</div>
</template>

<script lang="ts">
	import {
		Component,
		Prop,
		Watch,
		Vue
	} from 'vue-property-decorator'
	
	@Component
	export default class IScroll extends Vue {
		@Prop() private contentNum!: number;
		@Prop() private scrollList!: object[];
		
		cIndex: number = 0;
		observer!: any;
		
		get venderList(): object[]{
			return this.scrollList.slice(this.cIndex, this.cIndex + this.contentNum * 3);
		}
		get maxLength(): number{
			return this.scrollList.length;
		}
		@Watch('cIndex')
		cIndexChange(val: number){
			let parent: any = this.$refs.parent;
			parent.style.paddingTop = val * 36 + 'px';
			parent.style.paddingBottom = (this.maxLength - this.contentNum * 3 - val) * 36 + 'px';
		}
		
		getElementId(i: number){
			if(i === 0){
				return 'firstItem';
			}else if(i === (this.contentNum * 3 - 1)){
				return 'lastItem'
			}
		}
		
		scrollUp(){
			this.cIndex -= this.contentNum;
			if(this.cIndex < 0){
				this.cIndex = 0;
			}
		}
		
		scrollDown(){
			this.cIndex += this.contentNum;
			if((this.cIndex + this.contentNum * 3) > this.maxLength){
				this.cIndex = this.maxLength - this.contentNum * 3;
			}
		}
		
		mounted(){
			// 观察者创建
			this.observer = new IntersectionObserver((entries: any[]) => {
				entries.forEach((item: any) => {
					if(item.intersectionRatio > 0){
						// intersectionRatio: 0~1 之间，可见时大于0，不可见时小于等于0
						if(item.target.id === 'firstItem'){
							this.scrollUp();
						}else if(item.target.id === 'lastItem'){
							this.scrollDown();
						}
					}
				})
			});
			// 观察列表第一个以及最后一个元素
			this.observer.observe(this.$refs.firstItem[0]);
			this.observer.observe(this.$refs.lastItem[0]);
			
			this.cIndexChange(this.cIndex)
		}
	}
</script>

<style>
	.scroll-box{
		width: 200px;
		height: 180px;
		overflow-y: auto;
		padding: 0;
		margin: 0;
	}
	.infinity-scroll{
		list-style: none;
		padding: 0;
		margin: 0;
	}
	.infinity-scroll-item{
		padding: 8px;
		border: 1px solid #ccc;
		border-bottom-color: transparent; 
	}
	.infinity-scroll-item:nth-child(2n){
		background-color: #f3f5f4;
	}
	.infinity-scroll-item:last-child{
		border-bottom-color: #ccc; 
	}
</style>
